package com.ptt.sqm.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonParseException;

public class ListDeserializer implements JsonDeserializer<List> {

	@Override
	public List deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {

		List list = new ArrayList();
		try {
			if (!jsonElement.isJsonPrimitive()) {
				JsonArray jsonArray = jsonElement.getAsJsonArray();

				Gson gson= new GsonBuilder()    
				.registerTypeAdapter(Date.class, new DateDeserializer())
			    .registerTypeAdapter(List.class, new ListDeserializer())
			    .create();
				ParameterizedType pt = (ParameterizedType) type;
				Type genericType = pt.getActualTypeArguments()[0];

				for (JsonElement element : jsonArray) {
					// skipping the null here, if not null then parse json
					// element
					// and add in collection
					if (!(element instanceof JsonNull)) {
						list.add(gson.fromJson(element, genericType));
					}
				}
			} else {
				list = null;
			}
		} catch (Exception e) {
			list = null;
		}
		return list;
	}
}
